package plgloader

import (
	"fmt"
	"gitee.com/ymofen/gobase"
	"gitee.com/ymofen/gobase/getfrom"
	"gitee.com/ymofen/golang/refobjects"
	"gitee.com/ymofen/golang/strmap"
)

func InitalRefObjects() {
	refobjects.SetDefaultNewObjectFunc(func(conf string) (obj interface{}, err error) {
		obj, err = TryGetFrom(conf)
		if obj != nil {
			return obj, err
		}
		confMap := strmap.NewStrMap()
		confMap.URLFormDecode(conf)
		strType := confMap["type"]
		if len(strType) > 0 {
			return gobase.CreateFactoryInstance(strType, conf)
		} else {
			return nil, fmt.Errorf("invalid config %s", conf)
		}
	})
}

type GetFromWrapper struct {
	fn  getfrom.FuncGetFrom
	arg string
}

func (this *GetFromWrapper) ReadValue(args ...interface{}) (v interface{}, err error) {
	buf, err := this.fn(this.arg)
	return buf, err
}

func TryGetFrom(conf string) (obj interface{}, err error) {
	s1, s2 := gobase.Split2Str(conf, "://")
	if len(s1) == 0 {
		return nil, nil
	}
	fn := getfrom.GetFunc(s1)
	if fn == nil {
		return nil, nil
	}

	return &GetFromWrapper{fn: fn, arg: s2}, nil
}
